/*
 * @Author: tanjunyi@doctorwork.com
 * @Date: 2020-06-21 09:28:09
 * @LastEditors: tanjunyi@doctorwork.com
 * @LastEditTime: 2020-06-21 22:19:58
 * @Description:
 */
import { pushTarget, popTarget } from './dep'
import { queueWatcher } from './scheduler';
let id = 0; // 做一个watch 的id，每次创建时都有一个序号

class Watcher {
	constructor(vm, exprOrFn, cb, options) {
		this.vm = vm;
		this.exprOrFn = exprOrFn;
		this.cb = cb;
		this.options = options;
		this.deps = []; //存放所有的deps
		this.depsId = new Set();
		if (typeof exprOrFn === 'function') {
			this.getter = exprOrFn;
		}
		this.id = id++;
		this.get();
	}

	get() {
		pushTarget(this);
		this.getter();
		popTarget(this);
	}

	addDep(dep) {
		let id = dep.id;
		if (!this.depsId.has(id)) {
			this.depsId.add(id);
			this.deps.push(dep);
			dep.addSub(this);
		}
	}
	/**
	 * 更新视图渲染
	 */
	update() {
		console.log("wathcer:", this.id)
		// 异步更新队列
		queueWatcher(this); //将watcher存储起来
	}

	run() {
		this.get();
	}
}


export default Watcher;